<template>
  <view class="container">
    <view class="content-box">
      <view class="header-container">
        <scroll-view
          scroll-x="true"
          class="itembox"
          :scroll-into-view="currentScrollView"
          scroll-with-animation
        >
          <view class="header-scroll-box">
            <template v-if="filterType === 'loop'">
              <view
                v-for="(item, index) in LoopData"
                :key="index"
                class="header-card"
                :id="'card-' + index"
                @click="setActiveLoop(index, item.loop_id)"
                :class="{ 'active-card': activeLoopIndex === index }"
              >
                <text class="title">
                  {{ item.loop_name }}
                </text>
                <view class="bottom" :class="{ 'active-bottom': activeLoopIndex === index }">
                </view>
              </view>
            </template>
            <template v-else>
              <view
                v-for="(days, index) in dayCategories"
                :key="index"
                class="header-card"
                :id="'card-' + index"
                @click="setActiveLoop(index)"
                :class="{ 'active-card': activeLoopIndex === index }"
              >
                <text class="title">
                  {{ days }}天{{ days - 1 }}晚
                </text>
                <view class="bottom" :class="{ 'active-bottom': activeLoopIndex === index }">
                </view>
              </view>
            </template>
          </view>
        </scroll-view>
        <view class="filter-btn" @tap="showFilterOptions">
          <uni-icons type="bars" size="22"></uni-icons>

          <view class="filter-icon" :class="{ 'active': showFilter }">
            <text class="iconfont icon-arrow-down"></text>
          </view>
        </view>
      </view>
      
      <!-- 筛选选项弹出层 -->
      <view class="filter-options" v-if="showFilter">
        <view class="option" :class="{ 'active': filterType === 'loop' }" @tap="selectFilterType('loop')">
          <text>环线筛选</text>
        </view>
        <view class="option" :class="{ 'active': filterType === 'time' }" @tap="selectFilterType('time')">
          <text>时间筛选</text>
        </view>
      </view>

      <view class="itemboy">
        <view
          v-if="tripshopList && tripshopList.length > 0"
          class="describeCard"
          v-for="(item, index) in tripshopList"
          @click="toDetail(item.shop_id)"
        >
          <view class="imgBox">
            <image :src="imageUrl + item.cover_image" mode=""></image>
            <view class="labelFlex">
              <view class="label">
                <image
                  src="@/static/home/icon_design-tool_drafting-compass.png"
                  mode=""
                ></image>
                <text>{{ item.trip_day }}天{{ item.trip_night }}晚</text>
              </view>
              <text class="Selection">西望甄选</text>
            </view>
          </view>
          <view class="textBox">
            <text class="title">{{ item.title }}</text>
            <text class="deputyTitle">{{ item.subtitle }}</text>
            <text class="content">{{ item.description }}</text>
            <view class="tags">
              <view
                class="tags-card"
                v-for="(item_a, index_a) in item.label_list"
                :key="index_a"
              >
                <text>{{ item_a }}</text>
              </view>
            </view>
            <view class="footer-box">
              <view class="price">
                <text>￥</text>
                <text>{{ item.display_price }}</text>
                <text class="NumberPeople">/人起</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="noinfo">
          <text class="empty-icon">暂无数据</text>
          <text class="sub-text" v-if="filterType === 'loop'">该环线暂时没有相关行程，请看看其他环线吧~</text>
          <text class="sub-text" v-else>该天数暂时没有相关行程，请看看其他天数吧~</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getLoop ,getTripDay,getDayCategory} from "@/config/API/home.js";
import { GetTripshopList } from "@/config/API/ProductDetails.js";
import { routerGuard } from "@/config/RouteGuard.js";
import { imageUrl } from "../../config/request/request";

// 添加加载状态
const isLoading = ref(true);
// 添加时间类目数据
const dayCategories = ref([]);
// 添加当前选中的天数
const selectedDays = ref(null);

const fetchTripshopList = async (loop_id) => {
  try {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    const res = await GetTripshopList(loop_id);
    return res;
  } catch (e) {
    console.log(e);
    uni.showToast({
      title: "网络异常，请稍后重试",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

// 添加获取时间类目的方法
const fetchDayCategories = async () => {
  try {
    const res = await getDayCategory();
    if (res.code === 200) {
      dayCategories.value = res.data;
    } else {
      uni.showToast({
        title: "获取时间类目失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error(error);
    uni.showToast({
      title: "网络异常，请稍后重试",
      icon: "none",
    });
  }
};

// 添加根据天数获取行程的方法
const fetchTripByDays = async (days) => {
  try {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    const res = await getTripDay(days);
    if (res.code === 200) {
      tripshopList.value = res.data;
    } else {
      uni.showToast({
        title: "获取行程数据失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error(error);
    uni.showToast({
      title: "网络异常，请稍后重试",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

onLoad(async (options) => {
  try {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 获取时间类目数据
    await fetchDayCategories();
    
    // 如果是从"更多行程"跳转来的，直接切换到时间筛选
    if (options.filterType === 'time') {
      filterType.value = 'time';
      if (dayCategories.value.length > 0) {
        await fetchTripByDays(dayCategories.value[0]);
      }
    } else {
      // 默认加载环线数据
      const getLoopData = await getLoop();
      if (getLoopData.code == 200) {
        LoopData.value = getLoopData.data;
        if (LoopData.value && LoopData.value.length > 0) {
          loop_id.value = LoopData.value[0].loop_id;
          const res = await fetchTripshopList(loop_id.value);
          if (res.code == 200) {
            tripshopList.value = res.data || [];
          } else {
            uni.showToast({
              title: "数据获取失败",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: "暂无环线数据",
            icon: "none",
          });
        }
      } else {
        uni.showToast({
          title: "数据获取失败",
          icon: "none",
        });
      }
    }
  } catch (error) {
    console.error(error);
    uni.showToast({
      title: "网络异常，请稍后重试",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
});

//初始化的环线id
const loop_id = ref();
// 对应环线下商品数据
const tripshopList = ref([]);
// 环线数据
const LoopData = ref([]);
const activeLoopIndex = ref(0); // 用来记录当前选中的环线
const currentScrollView = ref(""); // 用于控制 scrollIntoView 的目标
const showFilter = ref(false);
const filterType = ref('loop'); // 默认环线筛选

// 修改setActiveLoop方法以支持时间筛选
const setActiveLoop = async (index, loop_id) => {
  if (filterType.value === 'loop') {
    activeLoopIndex.value = index; // 更新选中的环线索引
    currentScrollView.value = "card-" + index; // 设置 scroll-into-view 的值为点击的卡片 id
    const res = await fetchTripshopList(loop_id);
    if (res.code == 200) {
      tripshopList.value = res.data;
      console.log("tripshopList: ", tripshopList.value);
    } else {
      uni.showToast({
        title: "后台没数据了QAQ",
        icon: "none",
      });
      console.log("后台没数据");
    }
  } else if (filterType.value === 'time') {
    activeLoopIndex.value = index;
    currentScrollView.value = "card-" + index;
    selectedDays.value = dayCategories.value[index];
    await fetchTripByDays(selectedDays.value);
  }
};

const showFilterOptions = () => {
  showFilter.value = !showFilter.value;
};

// 修改筛选方式切换的方法
const selectFilterType = async (type) => {
  filterType.value = type;
  showFilter.value = false;
  activeLoopIndex.value = 0;
  currentScrollView.value = "card-0";
  
  if (type === 'loop') {
    // 先获取环线数据
    const getLoopData = await getLoop();
    if (getLoopData.code === 200) {
      LoopData.value = getLoopData.data;
      if (LoopData.value && LoopData.value.length > 0) {
        loop_id.value = LoopData.value[0].loop_id;
        const res = await fetchTripshopList(loop_id.value);
        if (res.code === 200) {
          tripshopList.value = res.data;
        }
      }
    }
  } else if (type === 'time' && dayCategories.value.length > 0) {
    await fetchTripByDays(dayCategories.value[0]);
  }
};

// 点击其他区域关闭筛选选项
onMounted(() => {
  document.addEventListener('click', (e) => {
    const filterBtn = document.querySelector('.filter-btn');
    const filterOptions = document.querySelector('.filter-options');
    if (!filterBtn?.contains(e.target) && !filterOptions?.contains(e.target)) {
      showFilter.value = false;
    }
  });
});

//点击进入详情
const toDetail = (id) => {
  const url = `/homeSubpages/ProductDetails/index?ShopId=${id}`;
  routerGuard(url);
};
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  background-color: #f5f5f5;

  .content-box {
    width: 100%;
    .header-container {
      position: relative;
      display: flex;
      align-items: center;
      background-color: #fff;
    }

    .itembox {
      white-space: nowrap;
      padding-right: 80rpx; // 为筛选按钮留出空间
      box-sizing: border-box;
    }

    .filter-btn {
      position: absolute;
      right: 0;
      top: 0;
      width: 80rpx;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: linear-gradient(to left, #fff 60%, rgba(255,255,255,0.8) 100%);
      z-index: 1;
      
      text {
        font-size: 24rpx;
        color: #333;
      }
      
      .filter-icon {
        transition: transform 0.3s;
        
        &.active {
          transform: rotate(180deg);
        }
      }
    }

    .filter-options {
      position: absolute;
      right: 20rpx;
      top: 80rpx;
      width: 160rpx;
      background-color: #fff;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
      z-index: 99;
      
      .option {
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &.active {
          color: #007AFF;
          font-weight: 500;
        }
      }
    }

    .header-scroll-box {
      display: flex;
      padding: 20rpx;
      padding-right: 100rpx; // 增加右侧内边距，确保最后一个选项完整显示
      box-sizing: border-box;
    }

    .header-card {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 40rpx;
      min-width: 120rpx; // 设置最小宽度
      padding: 10rpx 0;
      position: relative;
      
      &:last-child {
        margin-right: 20rpx; // 给最后一个卡片添加右边距
      }

      .title {
        font-size: 28rpx;
        color: #333;
        padding: 0 10rpx;
        transition: all 0.3s;
      }

      .bottom {
        width: 0;
        height: 4rpx;
        background-color: #007AFF;
        transition: all 0.3s;
        margin-top: 8rpx;
      }

      &.active-card {
        .title {
          color: #007AFF;
          font-weight: 500;
        }

        .bottom {
          width: 100%;
        }
      }
    }

    .itemboy {
      width: 100%;
      transition: all 0.5s;
      padding: 30rpx 32rpx;
      box-sizing: border-box;

      .describeCard {
        width: 100%;
        min-height: 450rpx;
        background-color: #fff;
        border-radius: 20rpx 20rpx 45rpx 45rpx;
        overflow: hidden;
        margin-bottom: 36rpx;

        border: 1rpx solid #dedede;

        .imgBox {
          width: 100%;
          height: 370rpx;
          position: relative;

          image {
            width: 100%;
            height: 100%;
            border-radius: 14rpx 14rpx 0 0;
          }

          .labelFlex {
            display: flex;
            align-items: center;
            gap: 15rpx;
            position: absolute;
            top: 25rpx;
            left: 20rpx;
            height: 30rpx;

            .label {
              display: flex;
              align-items: center;
              justify-content: center;
              padding: 0 10rpx;
              gap: 4rpx;
              height: 100%;
              border-radius: 6rpx;
              background: rgba(54, 48, 48, 1);
              font-size: 16rpx;
              font-weight: 400;
              color: rgba(232, 208, 149, 1);
              box-sizing: border-box;

              image {
                width: 20rpx;
                height: 20rpx;
              }
            }

            .Selection {
              font-size: 16rpx;
              font-weight: 400;
              line-height: 30rpx;
              color: #fff;
              background-color: rgba(4, 75, 173, 1);
              padding: 0rpx 10rpx;
              border-radius: 6rpx;
            }
          }
        }

        .textBox {
          width: 100%;
          padding: 26rpx;
          padding-bottom: 20rpx;
          box-sizing: border-box;

          text {
            display: block;
          }

          .title {
            font-size: 28rpx;
            font-weight: 700;
          }

          .deputyTitle {
            font-size: 26rpx;
            font-weight: 500;
          }

          .content {
            margin: 18rpx 0;
            font-size: 24rpx;
            color: rgba(125, 125, 125, 1);
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 7;
            overflow: hidden;
            text-overflow: ellipsis;
            // text-indent: 2em;
          }

          .tags {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            gap: 10rpx;

            .tags-card {
              padding: 10rpx 12rpx;
              border-radius: 12rpx;
              background-color: #f5f6f7;
              box-sizing: border-box;

              text {
                color: #888888;
                font-size: 24rpx;
              }
            }
          }

          .footer-box {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 20rpx 0;

            .price {
              display: flex;

              text {
                font-weight: 600;
              }

              .NumberPeople {
                margin-left: 10rpx;
                color: rgba(125, 125, 125, 1);
                font-weight: 500;
                font-size: 28rpx;
              }
            }

            .look {
              border-radius: 6rpx;
              border: 1rpx solid #000;
              padding: 10rpx;
              box-sizing: border-box;

              text {
                font-size: 34rpx;
              }
            }
          }
        }
      }

      .noinfo {
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 100rpx 0 0 0;
        box-sizing: border-box;
      }
    }
  }
}

.loading-state {
  width: 100%;
  height: 300rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  
  .loading-image {
    width: 80rpx;
    height: 80rpx;
    margin-bottom: 20rpx;
  }
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}

.noinfo {
  width: 100%;
  min-height: 400rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  box-sizing: border-box;
  
  .empty-icon {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 16rpx;
    &::before {
      content: "⚠️";
      margin-right: 8rpx;
    }
  }
  
  .sub-text {
    font-size: 26rpx;
    color: #999;
    text-align: center;
  }
}
</style>
